package com.pt25.base.dep.redis.aspect;


import cn.hutool.json.JSONObject;
import com.pt25.base.util.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;


@Slf4j
public class BaseCacheAspect {
    protected Method getMethod(ProceedingJoinPoint pjp) {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        return signature.getMethod();
    }

    /**
     * 缓存key前缀是方法返回的数据类型全名
     */
    protected String getDataCacheKey(ProceedingJoinPoint pjp, Method method, String cacheKey, String clazzName) {
        Class<?> returnType = method.getReturnType();
        String dataCacheKeyPre = returnType.getName();
        if (!clazzName.equals(Class.class.getName())) {
            dataCacheKeyPre = clazzName;
        }
        Parameter[] parameters = method.getParameters();
        Object[] args = pjp.getArgs();
        String dataCacheKey = null;
        for (int i = 0; i < args.length; i++) {
            //log.info("parameter:{};arg:{}", parameters[i], args[i]);
            String[] cacheKeys = cacheKey.split("\\.");
            if (cacheKeys[0].equals(parameters[i].getName())) {
                if (cacheKeys.length == 1) {
                    //如果是简单类型，cacheKey基于返回参数类型
                    dataCacheKey = dataCacheKeyPre + "&" + args[i];
                } else if (cacheKeys.length == 2) {
                    JSONObject argObj = JsonUtil.toBean(JsonUtil.toJson(args[i]), JSONObject.class);
                    assert argObj != null;
                    String key = argObj.getStr(cacheKeys[1]);
                    dataCacheKey = dataCacheKeyPre + "&" + key;
                }
                break;
            }
        }
        return dataCacheKey;
    }
}
